import { RouteRecordRaw } from "vue-router";
import { IBreadcrumb } from "@/base-ui/breadcrumb/type";
export function mapMenusToRoutes(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = [];

  // 动态加载文件（webpack）
  // 1.先去加载默认所有的routes
  const allRoutes: RouteRecordRaw[] = [];
  // 匹配.ts的文件
  // 第二个参数布尔值 是否按递归查找下面的文件
  // 该函数属于webpack里面的函数
  const routeFiles = require.context("../router/main", true, /\.ts/);
  routeFiles.keys().forEach((key) => {
    const route = require("../router/main" + key.split(".")[1]);
    allRoutes.push(route.default);
  });

  // 2.根据菜单获取需要添加的routes
  // userMenus:
  // type === 1 -> children -> type === 1
  // type === 2 -> url -> route
  const _recurseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        const route = allRoutes.find((route) => route.path === menu.url);
        if (route) routes.push(route);
      } else {
        _recurseGetRoute(menu.children);
      }
    }
  };

  _recurseGetRoute(userMenus);

  return routes;
}
export function mapMenusToPermissions(userMenus: any[]) {
  const permissions: string[] = [];

  const _recurseGetPermission = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 1 || menu.type === 2) {
        _recurseGetPermission(menu.children ?? []);
      } else if (menu.type === 3) {
        permissions.push(menu.permission);
      }
    }
    _recurseGetPermission(userMenus);
  };
  return permissions;
}
// 面包屑函数
// export function pathMapBreadcrumb(userMenus: any[], currentPath: string) {
//   const breadcrumbs: IBreadcrumb[] = [];

//   for (const menu of userMenus) {
//     if (menu.type === 1) {
//       const findMenu = pathMapBreadcrumb(menu.children ?? [], currentPath);
//       if (findMenu) {
//         breadcrumbs.push({ name: menu.name, path: menu.url})
//         breadcrumbs.push({ name: findMenu.name, path: findMenu.url})
//         return findMenu;
//       }
//       // pathMapBreadcrumb(menu.children ?? [], currentPath);
//     } else if (menu.type === 2 && menu.url === currentPath) {
//       return menu;
//     }
//   }
//   return breadcrumbs;
// }
//
export function pathMapMenu(userMenus: any[], currentPath: string): any {
  // const breadcrumbs: IBreadcrumb[] = [];

  for (const menu of userMenus) {
    if (menu.type === 1) {
      // const findMenu = pathMapBreadcrumb(menu.children ?? [], currentPath);
      // if (findMenu) {
      //   breadcrumbs.push({ name: menu.name, path: menu.url})
      //   breadcrumbs.push({ name: findMenu.name, path: findMenu.url})
      //   return findMenu;
      // }
      // 来一个递归调用
      const findMenu = pathMapMenu(menu.children ?? [], currentPath);
      if (findMenu) {
        return findMenu;
      }
    } else if (menu.type === 2 && menu.url === currentPath) {
      return menu;
    }
  }
}
